package com.dangz.dans.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dangz.dans.aes.SHA1;
import com.dangz.dans.aes.XMLParse;
import com.dangz.dans.entity.CommonResponse;
import com.dangz.dans.model.News;
import com.dangz.dans.model.wx.Reply;
import com.dangz.dans.model.wx.Setting;
import com.dangz.dans.model.wx.SubscribeInfo;
import com.dangz.dans.service.ReplyServiceImpl;
import com.dangz.dans.service.SettingServiceImpl;
import com.dangz.dans.service.SubscribeInfoServiceImpl;
import com.dangz.dans.response.ApiEnum;
import com.dangz.dans.response.CodeEnum;
import com.dangz.dans.response.TypeEnum;
import com.dangz.dans.utils.DateUtils;
import com.dangz.dans.utils.RedisUtil;
import com.dangz.dans.utils.ResponseUtils;
import com.dangz.dans.utils.WxUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author dangz
 * @since 2018/1/29 14:35
 */
@RestController
@RequestMapping("dans/wx")
@Api(tags = "微信入口")
public class WxController {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private SubscribeInfoServiceImpl subscribeInfoService;
    @Autowired
    private SettingServiceImpl settingService;
    @Autowired
    private ReplyServiceImpl replyService;

    private final String appid = "wx0998c6284abdd630";
    private final String secret = "d4624c36b6795d1d99dcf0547af5443d";

    @ApiOperation(value = "微信入口", notes = "POST方式")
    @GetMapping("entrance")
    public void weixinEnter(HttpServletRequest request, HttpServletResponse response, String signature, String timestamp, String nonce, String echostr) {
        try {
            response.setContentType("text/html;charset=utf-8");
            if (StringUtils.isNotEmpty(echostr)) {
                if (SHA1.checkSignature(signature, timestamp, nonce)) {
                    ResponseUtils.render(response, "text/html", echostr);
                    System.out.print(echostr);
                }
            } else {
                InputStream in = request.getInputStream();
                int len = 0;
                byte[] buffer = new byte[1024];
                ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                while ((len = in.read(buffer)) != -1) {
                    outStream.write(buffer, 0, len);
                }
                byte[] data = outStream.toByteArray();// 网页的二进制数据
                String re = new String(data, "utf-8");
                //https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET 获取access_token接口
                System.out.println(re);
                Object[] o = XMLParse.denctryXml(re);
                String from = o[3] + "";
                String to = o[2] + "";
                Setting setting = settingService.findByOriginalCode(to);
                String dataTime = DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss");
                if (o[1].equals("event")){
                    //拉取粉丝
                    if (o[4].equals("subscribe")){
                        /**
                         * 回复集合
                         */
                        List<Reply>  replys = replyService.findAll(setting.getCode());
                        List<News> news = new ArrayList<News>();
                        News n = null;
                        for (Reply reply : replys) {
                            n = new News();
                            n.setDesc(reply.getContent());
                            n.setHttpurl(reply.getUrl());
                            n.setTitle(reply.getTitle());
                            n.setUrl(reply.getImgurl());
                            news.add(n);
                        }
                        //回复封装
                        String str = XMLParse.newsType(from, to, news);
                        ResponseUtils.render(response,"text/html", str); //关注回复

//                        String token = WxUtils.getAccessToken(appid , secret, redisUtil);
                        JSONObject obj = WxUtils.getUserInfo(appid, secret, redisUtil, from);
                        System.out.println(obj.toJSONString());
                        obj.remove("tagid_list");
                        if (obj.get("errcode") == null){ // 表示拉取用户信息成功
                            SubscribeInfo subscribeInfo = subscribeInfoService.findByOpenidAndPid(from, setting.getCode());
                            SubscribeInfo subscribeInfo1 = JSON.parseObject(obj.toJSONString(), SubscribeInfo.class);
                            if (subscribeInfo == null){
                                subscribeInfo = new SubscribeInfo();
                                BeanUtils.copyProperties(subscribeInfo1, subscribeInfo);
                                subscribeInfo.setPid(setting.getCode());
                                subscribeInfo.setSubscribe_time(dataTime);
                            } else {
                                BeanUtils.copyProperties(subscribeInfo1, subscribeInfo,
                                        new String[]{"id","subscribe_time","unsubscribeTime","pid"});
                            }
                            subscribeInfoService.save(subscribeInfo);
                        }
                    }else if (o[4].equals("unsubscribe")){ //取消关注
                        SubscribeInfo subscribeInfo = subscribeInfoService.findByOpenidAndPid(from, setting.getCode());
                        subscribeInfo.setSubscribe("0");
                        subscribeInfo.setUnsubscribeTime(dataTime);
                        subscribeInfoService.save(subscribeInfo);
                    }else if (o[4].equals("poi_check_notify")){
                        //门店审核通知
						/*<xml><ToUserName><![CDATA[gh_a78acf2619a1]]></ToUserName>
						<FromUserName><![CDATA[o4iGFjgNXMveefz_Gszi3LmtjSY0]]></FromUserName>
						<CreateTime>1441945667</CreateTime>
						<MsgType><![CDATA[event]]></MsgType>
						<Event><![CDATA[poi_check_notify]]></Event>
						<UniqId><![CDATA[5]]></UniqId>
						<PoiId>294345162</PoiId>
						<result><![CDATA[succ]]></result>
						<msg><![CDATA[]]></msg>
						</xml>*/

                        ResponseUtils.render(response,"text/html", "");
                    }else if (o[4].equals("WifiConnected")){ //用户连上wifi
                        //调用客户接口推送消息from为用户Openid mac - DeviceNo
						/*<xml>
						<ToUserName><![CDATA[toUser]]></ToUserName>
						<FromUserName><![CDATA[FromUser]]></FromUserName>
						<CreateTime>123456789</CreateTime>
						<MsgType><![CDATA[event]]></MsgType>
						<Event><![CDATA[WifiConnected]]></Event>
						<ConnectTime>0</ConnectTime>
						<ExpireTime>0</ExpireTime>
						<VendorId>![CDATA[3001224419]]</VendorId>
						<PlaceId>![CDATA[PlaceId]]</PlaceId>
						<DeviceNo>![CDATA[DeviceNo]]</DeviceNo>
						</xml>*/
                        ResponseUtils.render(response,"text/html", "");  //回复通知
                    }
                }else if (o[1].equals("text")){
                    /**
                     * <xml><ToUserName><![CDATA[gh_cf2cd6bb8812]]></ToUserName>
                     <FromUserName><![CDATA[oXMR1txIktr2P217vC0WamGWNXJ0]]></FromUserName>
                     <CreateTime>1476685193</CreateTime>
                     <MsgType><![CDATA[text]]></MsgType>
                     <Content><![CDATA[。]]></Content>
                     <MsgId>6342314610833811918</MsgId>
                     </xml>
                     */
                    System.out.println(o[5]+"------------接收消息");
                    //to 关联的公众号
                    //搜索内容。
                    List<Reply>  replys = replyService.findAll(setting.getCode());
                    List<News> news = new ArrayList<News>();
                    News ns = null;
                    for (Reply reply : replys) {
                        ns = new News();
                        ns.setDesc(reply.getContent());
                        ns.setHttpurl(reply.getUrl());
                        ns.setTitle(reply.getTitle());
                        ns.setUrl(reply.getImgurl());
                        news.add(ns);
                    }
                    //回复封装
                    String n = XMLParse.newsType(from, to, news);
                    System.out.println(n);
                    ResponseUtils.render(response,"text/html", n); //关注回复

                    //测试发送模板消息
                    //ok
                 /*   JSONObject obj = new JSONObject();
                    obj.put("touser", from);
                    obj.put("template_id", "o_VadhPL85vGPXS1-QoyV-rwA0UaaOid7BE-9juFmAg");
                    obj.put("url", "");
                    obj.put("topcolor", "#FF0000");
                    JSONObject data_obj = new JSONObject();
                    JSONObject valueObj = new JSONObject();
                    valueObj.put("value", "测试");
                    valueObj.put("color", "#173177");
                    data_obj.put("first", valueObj);

                    valueObj = new JSONObject();
                    valueObj.put("value", "huangse");
                    valueObj.put("color", "#173177");
                    data_obj.put("key", valueObj);
                    valueObj = new JSONObject();
                    valueObj.put("value", "123");
                    valueObj.put("color", "#173177");
                    data_obj.put("key1", valueObj);
                    System.out.println(data_obj.toJSONString());
                    obj.put("data", data_obj);
                    System.out.println(obj.toJSONString());

                    WxUtils.sendTemplate(setting.getAppid(), setting.getSecret(), redisUtil, obj);*/
                }else{

                }
//                ResponseUtils.render(response,"text/html", "");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @ApiOperation(value = "获取ACCESS_TOKEN", notes = "POST方式")
    @ApiImplicitParams({
//            @ApiImplicitParam(paramType = "header", value = "Authorization", name = HttpHeaders.AUTHORIZATION, dataType = "String")
            @ApiImplicitParam(paramType = "query", name = "appid", value = "APPID", dataType = "String", required = true),
            @ApiImplicitParam(paramType = "query", name = "secret", value = "SECRET", dataType = "String", required = true)
    })
    @GetMapping("getToken")
    public CommonResponse findByCode(String appid, String secret) {
        CommonResponse commonResponse = null;
        String token = WxUtils.getAccessToken(appid, secret, redisUtil);
        if (StringUtils.isNotEmpty(token)) {
            commonResponse = new CommonResponse(TypeEnum.getFullRespCode(TypeEnum.Success,
                    ApiEnum.XTGL, CodeEnum.SUCCESS_SERVICE_LOCAL), CodeEnum.SUCCESS_SERVICE_LOCAL.getInfo(), token);
        } else {
            commonResponse = new CommonResponse(TypeEnum.getFullRespCode(TypeEnum.Success,
                    ApiEnum.XTGL, CodeEnum.SUCCESS_NO_DATA_LOCAL), CodeEnum.SUCCESS_NO_DATA_LOCAL.getInfo());
        }
        return commonResponse;
    }


}
